<template>
  <a-card :bordered="false" :bodyStyle="{paddingTop:'0px',position:'relative'}">
    <div style="position: absolute;right:50px;z-index: 100;top: 10px;width: 550px;height:30px;text-align: right">
      <a-form  @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="12" :sm="12" v-if="currentTab === '0'" >
            <a-form-item>
              <a-date-picker
                valueFormat='YYYY-MM-DD HH:mm:ss'
                :default-value="queryParam.startTime"
                @change="startTimeChange"
              />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-form-item>
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              </a-form-item>
            </span>
          </a-col>
          <a-col :md="4" :sm="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-form-item>
                <a-button v-if="currentTab === '0'" @click="openCommonDailyModel" type="primary">新增通用</a-button>
              </a-form-item>
            </span>
          </a-col>
          <a-col :md="4" :sm="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-form-item>
                <a-button v-if="currentTab === '0'" @click="handleWorkTasksBatch" type="primary">批量填报</a-button>
              </a-form-item>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-tabs v-model="currentTab" @change="callback">
      <a-tab-pane key="0" tab="我负责"></a-tab-pane>
      <a-tab-pane key="1" tab="待我审核"></a-tab-pane>
      <a-tab-pane key="2">
        <template slot="tab">
          <a-dropdown >
            <span>{{tabName}} <a-icon type="down" /></span>
            <a-menu v-model="current" slot="overlay" @click="handleMenuClick">
               <a-menu-item key="0" title="全部">
                <a >全部</a>
              </a-menu-item>
              <a-menu-item key="1" title="我审核">
                <a >我审核</a>
              </a-menu-item>
              <a-menu-item key="2" title="抄送我的">
                <a >抄送我的</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-tab-pane>
    </a-tabs>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
        class="j-table-force-nowrap"
        >
        <template slot="tasklevel" slot-scope="text,record">
          <a-tag v-if="record.taskLevel === '0'">普通</a-tag>
          <a-tag v-else-if="record.taskLevel === '1'" color="blue">重要</a-tag>
          <a-tag v-else-if="record.taskLevel === '2'" color="orange">紧急</a-tag>
          <a-tag v-else-if="record.taskLevel === '3'" color="red">重要紧急</a-tag>
        </template>
        <template slot="taskProgress" slot-scope="text,record">
          <a-progress :showInfo="true" :percent="record.taskProgress" />
        </template>
        <!--今日工时填报-->
        <template slot="todayHours" slot-scope="text, record,index">
          <div>
            <a-input-number v-if="record.taskStatus<=1" :min="0" :max="24" v-model="dataSource[index].taskTime.manHours" @blur="updateProgress(dataSource[index])"  placeholder="今日工时"/>
            <span v-else>{{dataSource[index].taskTime.manHours}}</span>
          </div>
        </template>
        <!--任务进度填报-->
        <template slot="updateProgress" slot-scope="text, record,index">
          <div>
            <a-input-number v-if="record.taskStatus<=1" :min="0" :max="100" v-model="dataSource[index].taskTime.taskProgress"  placeholder="更新完成比"/>
            <span v-else>{{dataSource[index].taskTime.taskProgress}}</span>
          </div>
        </template>
        <!--今日工作开始时间-->
<!--        <template slot="todayStartTime" slot-scope="text, record,index">-->
<!--          <div>-->
<!--            <a-date-picker show-time v-if="record.taskStatus<=1" valueFormat="YYYY-MM-DD HH:mm:ss" v-model="record.todayStartTime"/>-->
<!--          </div>-->
<!--        </template>-->
        <!--工作内容-->
        <template slot="workContent" slot-scope="text, record,index">
          <div>
            <a-textarea :rows="1" v-if="record.taskStatus<=1" valueFormat="YYYY-MM-DD HH:mm:ss" v-model="dataSource[index].taskTime.remarks"/>
            <span v-else>{{dataSource[index].taskTime.remarks}}</span>
          </div>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="isCanEdit(record)" @click="handleWorkTask(record)">填报</a>
          <a-divider v-if="isCanEdit(record)" type="vertical" />
          <a  @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-if="isCanCheck(record)">
                <a @click="handleCheckTask(record)">审核</a>
              </a-menu-item>
              <!--<a-menu-item v-if="isCanEdit(record) && record.taskStatus === '0'">
                <a @click="handleStart(record)">开始</a>
              </a-menu-item>-->
              <a-menu-item>
                <a v-if="isCanEdit(record)" @click="handleEditTask(record)">编辑</a>
              </a-menu-item>
              <a-menu-item v-if="isCanEdit(record) && record.taskStatus === '1'">
                <a @click="handleTaskTime(record)">填写工时</a>
              </a-menu-item>
              <!-- <a-menu-item v-if="isCanEdit(record)">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item> -->
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <my-project-list-modal ref="ProjectTaskModal" @ok="handleOk" :projectCode="projectCode"></my-project-list-modal>
    <project-task-time-modal ref="ProjectTaskTimeModal" @ok="handleOk"></project-task-time-modal>
    <a-modal v-model="addCommonVisible" title="新增通用日报" ok-text="确认" cancel-text="取消" @ok="addToTable">
      <a-form>
        <a-form-item
          label="日报类型"
          :labelCol="{span:4}"
          :wrapperCol="{span:20}"
          style="margin-bottom:10px"
          :validate-status="validate_status">
          <JSearchSelectTag dict="pms_common_task_type" v-model="addDailyType"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, putAction,postAction } from '@/api/manage'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { mapGetters } from 'vuex'
import MyProjectListModal from './modal/MyProjectListModal'
import ProjectTaskTimeModal from './modal/ProjectTaskTimeModal'
import moment from 'moment';
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
export default {
  name: 'MyProjectList',
  mixins: [JeecgListMixin],
  components: {
    MyProjectListModal,
    ProjectTaskTimeModal,
    JSearchSelectTag
  },
  data() {
    return {
      columns: [// 表头
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '项目名称',
          align: 'center',
          customRender: function(t, r, index) {
            if (r.taskType === 'common') {
              return "通用"
            }else{
              return t.projectCode_dictText;
            }
          }
        },
        {
          title: '任务名称',
          align: 'center',
          // dataIndex: 'taskName'
          customRender: function(t, r, index) {
            return t.taskCode + " " +r.taskName
          }
        },
        // {
        //   title: '任务编号',
        //   align: 'center',
        //   dataIndex: 'taskCode'
        //
        // },
        {
          title: '任务状态',
          align: 'center',
          dataIndex: 'taskStatus',
          customRender: function(t, r, index) {
            return filterDictTextByCache('pms_task_status', t)
          },
          filters: [
            { text: '进行中', value: '0' },
            { text: '已完成', value: '1' },
            { text: '全部', value: '2' }
          ],
          // filteredValue: ['0'],
          filterMultiple: false
          // onFilter: this.tableFilter
        },
        // {
        //   title: '开始',
        //   align: 'center',
        //   dataIndex: 'startTime'
        // },
        {
          title: '预计结束',
          align: 'center',
          dataIndex: 'endTime'
        },
        {
          title: '任务分级',
          align: 'center',
          dataIndex: 'tasklevel',
          scopedSlots: { customRender: 'tasklevel' }
        },
        {
          title: '完成比',
          align: 'center',
          dataIndex: 'taskProgress',
          scopedSlots: { customRender: 'taskProgress' }
        },

        {
          title: '前置任务',
          align: 'center',
          dataIndex: 'preTaskCode'
        },
        // {
        //   title: '预计工时',
        //   align: 'center',
        //   dataIndex: 'planManHours'
        // },
        {
          title: '实际工时',
          align: 'center',
          dataIndex: 'actualManHours'
        },
        {
          title: '今日工时',
          align: 'center',
          dataIndex: 'todayHours',
          scopedSlots: { customRender: 'todayHours' }
        },
        {
          title: '更新完成比',
          align: 'center',
          dataIndex: 'updateProgress',
          scopedSlots: { customRender: 'updateProgress' }
        },
        // {
        //   title: '开始时间',
        //   align: 'center',
        //   dataIndex: 'todayStartTime',
        //   scopedSlots: { customRender: 'todayStartTime' }
        // },
        {
          title: '工作内容',
          align: 'center',
          dataIndex: 'workContent',
          scopedSlots: { customRender: 'workContent' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/pms/task/list',
        queryByCode: '/pms/task/queryByCode',
        edit: '/pms/task/edit',
        addWorkHours: '/pms/taskTime/addWorkHours',
        addWorkHoursBatch: '/pms/taskTime/addWorkHoursBatch'
      },
      tabName: '全部',
      current: ['0'],
      currentTab: '0',
      filteredValue: '',
      projectCode: '',
      queryParam: {},
      addCommonVisible: false,
      addDailyType: ''
    }
  },
  computed: {
    username() {
      return this.userInfo().username
    }
  },
  mounted() {

  },
  methods: {
    moment,
    ...mapGetters(['userInfo']),
    callback() {
      this.loadData()
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      params.hasChildren = 0
      params = Object.assign(params, this.getParamsByTab())
      console.log(params)
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getParamsByTab() {
      if (this.currentTab === '0') {
        let obj = { taskDirector: this.userInfo().username }
        if (!this.queryParam.startTime) {
          obj.startTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
          this.queryParam.startTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        }
        obj = Object.assign(obj, this.getTaskStatus())
        return obj
      } else if (this.currentTab === '1') {
        return {
          taskReviewer: this.userInfo().username,
          taskStatus: 2
        }
      } else if (this.currentTab === '2' && this.current[0] === '0') {
        const data = [
          { 'rule': 'eq', 'type': 'text', 'val': this.userInfo().username, 'field': 'taskReviewer' },
          { 'rule': 'eq', 'type': 'text', 'val': this.userInfo().username, 'field': 'taskDirector' },
          { 'rule': 'eq', 'type': 'text', 'val': this.userInfo().username, 'field': 'taskCclist' },
          { 'rule': 'right_like', 'type': 'text', 'val': this.userInfo().username + ',', 'field': 'taskCclist' },
          { 'rule': 'like', 'type': 'text', 'val': ',' + this.userInfo().username + ',', 'field': 'taskCclist' },
          { 'rule': 'left_like', 'type': 'text', 'val': ',' + this.userInfo().username, 'field': 'taskCclist' },
          { 'rule': 'ne', 'type': 'text', 'val': '1', 'field': 'hasChildren' }
        ]
        return {
          // taskReviewer: this.userInfo().username,
          // taskDirector: this.userInfo().username,
          // taskCclist: this.userInfo().username,
          superQueryMatchType: 'or',
          superQueryParams: encodeURIComponent(JSON.stringify(data))
        }
      } else if (this.currentTab === '2' && this.current[0] === '1') {
        let obj = { taskReviewer: this.userInfo().username }
        obj = Object.assign(obj, this.getTaskStatus())
        return obj
      } else if (this.currentTab === '2' && this.current[0] === '2') {
        let obj = { taskCclist: this.userInfo().username }
        obj = Object.assign(obj, this.getTaskStatus())
        return obj
      }
    },
    getTaskStatus() { // 根据表格过滤状态构造参数
      if (this.filteredValue === '0') {
        return {
          taskStatus_begin: '0',
          taskStatus_end: '2'
        }
      } else if (this.filteredValue === '1') {
        return {
          taskStatus: '3'
        }
      } else {
        return {}
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.ipagination.current = 1
      this.filteredValue = filters.taskStatus[0]
      this.loadData()
    },
    handleMenuClick({ item, key }) {
      this.tabName = item.title
      this.current = [key]
      this.currentTab = '2'
      this.loadData()
    },
    handleEditTask(data) {
      this.projectCode = data.projectCode
      this.$refs.ProjectTaskModal.edit(data)
    },
    handleDetail(data) {
      this.$refs.ProjectTaskModal.disableSubmit = true
      this.$refs.ProjectTaskModal.edit(data)
    },
    handleCheckTask(data) {
      this.$refs.ProjectTaskModal.isCheck = true
      this.$refs.ProjectTaskModal.disableSubmit = true
      this.$refs.ProjectTaskModal.edit(data)
    },
    handleTaskTime(data) {
      this.$refs.ProjectTaskTimeModal.show(data.taskCode)
    },
    async handleStart(data) {
      if (!data.preTaskCode) {
        data.taskStatus = '1'
        this.editTask(data)
        return false
      }
      try {
        const res = await getAction(this.url.queryByCode, { code: data.preTaskCode })
        if (!res.success) {
          this.$message.warning(res.message)
          return false
        }
        if (res.result.taskStatus !== '3') {
          this.$message.warning('前置任务未完成，不允许开始')
          return false
        }
        data.taskStatus = '1'
        this.editTask(data)
      } catch (err) {
        console.log(err)
      }
    },
    editTask(data) {
      putAction(this.url.edit, data).then(res => {
        if (!res.success) {
          this.$message.warning(res.message)
          return false
        }
        this.$message.success('任务已开始')
      })
    },
    handleOk() {
      this.loadData()
    },
    isCanCheck(data) {
      if (data.taskReviewer) {
        const taskReviewers = data.taskReviewer.split(',')
        if (data.taskStatus === '2' && taskReviewers.indexOf(this.username) >= 0) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    isCanEdit(data) {
      if (data.taskDirector) {
        const taskDirector = data.taskDirector.split(',')
        if ((data.taskStatus === '0' || data.taskStatus === '1') && taskDirector.indexOf(this.username) >= 0) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    // 工时填报
    async handleWorkTask(data) {
      // 判断工时、开始时间以及内容是否已填
      if (!data.taskTime.manHours) {
        this.$message.warning("请填写工时")
        return
      }
      if (!data.taskTime.taskProgress) {
        this.$message.warning("请填写完成比")
        return
      }
      // 完成参数key的转换
      data.startTime = this.queryParam.startTime
      data.manHours = data.taskTime.manHours
      data.remarks = data.taskTime.remarks
      var taskOldProgress = data.taskProgress
      data.taskProgress = data.taskTime.taskProgress
      data.projectCode = data.projectCode
      data.id = data.taskTime.id
      console.log(data)
      // 判断工时是否已经开始，如果未开始，需要判断前置工单是否已经完成
      if (data.preTaskCode) {
        try {
          const res = await getAction(this.url.queryByCode, {code: data.preTaskCode});
          if (!res.success) {
            this.$message.warning(res.message)
            return false
          }
          if (res.result.taskStatus !== '3') {
            this.$message.warning('前置任务未完成，不允许开始')
            return false
          }
        }catch (e) {
          console.log(e);
        }

      }
      // 请求进行工时累加
      delete data['createTime'];
      delete data['createBy'];
      delete data['updateTime'];
      delete data['updateBy'];
      postAction(this.url.addWorkHours, data).then(res =>{
        if (!res.success) {
          this.$message.warning(res.message)
          data.taskProgress = taskOldProgress
          return false
        }else{
          this.$message.success("填报成功");
          this.loadData();
        }

      })
    },

    // 批量填报工时
    handleWorkTasksBatch(){
      console.log(this.dataSource)
      let dataSource = this.dataSource;
      let params = [];

      // 数据清洗，有效数据组装
      for (let i = 0; i < dataSource.length; i++) {
        debugger
        let dataSourceElement = dataSource[i];
        var taskTime = dataSourceElement.taskTime;
        // 三项内容都未填写，代表不做此task的提交
        if (!taskTime.manHours && !taskTime.taskProgress) {
          continue;
        }
        // // 检验三项中是否有漏填项目
        // if (!dataSourceElement.manHours || !dataSourceElement.taskProgress) {
        //   this.$message.warning("任务："+dataSourceElement.taskName+" 请填写完整");
        //   return
        // }
        // 组装进入入参数组中
        let param = {};
        param.projectCode = dataSourceElement.projectCode;
        param.taskCode = dataSourceElement.taskCode;
        param.taskProgress = taskTime.taskProgress;
        param.startTime = this.queryParam.startTime;
        param.manHours = taskTime.manHours;
        param.remarks = taskTime.remarks;
        param.id = taskTime.id

        params.push(param);
      }
      console.log(params)
      postAction(this.url.addWorkHoursBatch, params).then(res =>{
        if (!res.success) {
          this.$message.warning(res.message)
          return false
        }else{
          this.$message.success("填报成功");
          this.loadData();
        }

      })
    },
    // todo 根据今日工时，自动更新完成比
    updateProgress(record){
      console.log(record.todayHours);
      // record.planManHours

    },
    startTimeChange(date, dateString){
      this.queryParam.startTime = date;
    },
    // 打开新增通用日报的弹窗
    openCommonDailyModel(){
      this.addCommonVisible = true
    },
    addToTable() {
      console.log(this.addDailyType);
      if (!this.addDailyType) {
        this.$message.error('请选择类型!')
        return
      }
      this.addCommonVisible = false;
      const newData = {};
      newData.rowIndex = this.dataSource.length + 1;
      newData.projectCode_dictText = '通用';
      newData.projectCode = 'common';
      newData.taskType = 'common';
      newData.taskName = '会议';
      newData.taskCode = this.addDailyType;
      newData.parentTaskCode = 0;
      newData.startTime= moment(new Date()).format('YYYY-MM-DD');
      newData.endTime = moment(new Date()).format('YYYY-MM-DD');
      newData.taskDirector = this.userInfo().username;
      newData.taskStatus = '0';
      newData.taskProgress = 100;
      newData.taskTime={
        taskProgress : 100,
        remarks : '',
        manHours: ''
      }

      this.dataSource = [...this.dataSource, newData];
    }
  }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
